package com.us.usws.dao;

import java.util.List;

import net.iwsh.core.db.DBExecutor;
import net.iwsh.core.db.ext.DialectSyntaxParser;
import net.iwsh.core.db.ext.SQLWithParams;
import net.iwsh.core.utils.IDGenerator;

import com.us.usws.model.domain.system.Dept;
import com.us.usws.model.flat.system.DODept;

public class DeptDAO {

	/***
	 * get SQLs
	 */
	private static final String SQL_GET_DEPT_BY_UID = "select * from sys_dept where uid=?";
	private static final String SQL_GET_ALL_DEPTS = "select * from sys_dept";

	/**
	 * CUD SQLs
	 */
	private static final String SQL_INSERT_DEPT = "insert into sys_dept(uid,name,parent_uid,is_valid,description) values (?,?,?,?,?)";
	private static final String SQL_UPDATE_DEPT = "update sys_dept set name=?, parent_uid=?, is_valid=?, description=? where uid=?";
	private static final String SQL_UPDATE_DEPT_IS_VALID = "update sys_dept set is_valid=? where uid=?";
	private static final String SQL_DEL_DEPT = "delete from sys_dept where uid=?";

	/**
	 * DBExeutor
	 */
	private DBExecutor dbe = new DBExecutor();

	/**
	 * get dept by uid
	 * @param uid
	 * @return
	 */
	public Dept getDept(String uid) {
		Dept d = dbe.load(SQL_GET_DEPT_BY_UID, Dept.class, uid);
		return d;
	}

	/**
	 * get dept count
	 * @return
	 */
	public int getDeptCount() {
		String sql = DialectSyntaxParser.getParser().getCountSQL(SQL_GET_ALL_DEPTS);
		return dbe.getCount(sql);
	}

	/**
	 * get all depts
	 * @return
	 */
	public List<Dept> getAllDepts() {
		return dbe.list(SQL_GET_ALL_DEPTS, Dept.class);
	}

	/**
	 * get depts by pagination
	 * @param start
	 * @param end
	 * @return
	 */
	public List<Dept> getDepts(int start, int end) {
		SQLWithParams swp = DialectSyntaxParser.getParser().getPaginationSQLWithParams(SQL_GET_ALL_DEPTS, null, start, end);
		return dbe.list(swp.getSql(), Dept.class, swp.getParams());
	}

	/**
	 * insert dept
	 * @param dept
	 * @return
	 */
	public String insertDept(DODept dept) {
		String uid = IDGenerator.getInstance().genUID();
		dept.setUid(uid);
		dbe.execute(SQL_INSERT_DEPT, uid, dept.getName(), dept.getParentUid(), dept.getIsValid(), dept.getDescription());
		return uid;
	}

	/**
	 * update dept
	 * @param dept
	 */
	public void updateDept(DODept dept) {
		dbe.execute(SQL_UPDATE_DEPT, dept.getName(), dept.getParentUid(), dept.getIsValid(), dept.getDescription(), dept.getUid());
	}

	/**
	 * update is valid flag
	 * @param uid
	 * @param isValid
	 */
	public void updateIsValid(String uid, String isValid) {
		dbe.execute(SQL_UPDATE_DEPT_IS_VALID, isValid, uid);
	}

	/**
	 * delete dept
	 * @param uid
	 */
	public void deleteDept(String uid) {
		dbe.execute(SQL_DEL_DEPT, uid);
	}

}
